import json

from django.shortcuts import render, HttpResponse

# Create your views here.
from .models import Book


def add_book(request):
    book = Book(name="兄弟", author="余华", price=100.0, pub_time="2023-07-13")
    book2 = Book(name="活着", author="余华", price=50.0, pub_time="2000-08-25")
    book3 = Book(name="天堂旅行团", author="张嘉佳", price=80.0, pub_time="2020-04-26")
    book.save(), book2.save(), book3.save()
    return HttpResponse("添加图书成功")


def query_book(request):
    book = Book.objects.all()
    return render(request, "query_book.html", {"book": book})


def query_book_by_id(request, book_id):
    book = Book.objects.get(pk=book_id)
    return render(request, "query_book_by_id.html", {"book": book})


# def update_book(request, updateBook):
#     book = Book(name=updateBook.name,author=updateBook.author,price=updateBook.price,pub_time=updateBook.pub_time).json.loads(request.body)
#     book.save()
#     return HttpResponse("修改图书成功")

def update_book(request, updateBook):
    book = Book.objects.get(pk=updateBook)
    # book.update(name=updateBook.name, author=updateBook.author, price=updateBook.price, pub_time=updateBook.pub_time)
    print(updateBook)
    book.name = input("请输入书名:")
    book.author = input("请输入作者:")
    book.price = float(input("请输入价格:"))
    book.pub_time = input("请输入出版时间:")
    book.save()

    return HttpResponse("数据修改成功")


def delete_book(request, book_id):
    book = Book.objects.get(id=book_id)
    book.delete()
    return HttpResponse("删除图书成功")
